using BuildingBlocks.Abstractions.EventBase;
using BuildingBlocks.Abstractions.Permissions;
using Identity.Domain.Aggregates;
using Identity.Infrastructure.Persistence.Entities;
using Microsoft.Extensions.Logging;

namespace Identity.Infrastructure.EventHandlers
{
    public class PermissionRegisteredEventHandler
    : IIntegrationEventHandler<PermissionRegisteredEvent>
    {
        private readonly ApplicationDbContext _db;
        private readonly ILogger<PermissionRegisteredEventHandler> _logger;

        public PermissionRegisteredEventHandler(ApplicationDbContext db, ILogger<PermissionRegisteredEventHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task HandleAsync(PermissionRegisteredEvent @event)
        {
            _logger.LogInformation($"开始处理权限注册事件，服务：{@event.ServiceName}");
            
            var existingBindings = _db.ApiPermissionBindings
                .Where(a => a.FromServiceName == @event.ServiceName)
                .ToList();

            var existingResourceIds = existingBindings.Select(b => b.ResourceId).ToHashSet();
            var incomingResourceIds = @event.Permissions.Select(p => p.resourceId).ToHashSet();

            var toDelete = existingBindings.Where(b => !incomingResourceIds.Contains(b.ResourceId)).ToList();
            _db.ApiPermissionBindings.RemoveRange(toDelete);

            var toAdd = @event.Permissions
                .Where(p => !existingResourceIds.Contains(p.resourceId))
                .Select(p => ApiPermissionBinding.Create(
                        p.resourceId,
                        p.description,
                        @event.ServiceName,
                        Domain.ValueObjects.PermissionScope.Local))
                        .ToList();

            _db.ApiPermissionBindings.AddRange(toAdd);
            await _db.SaveChangesAsync();
            _logger.LogInformation($"完成权限注册事件， 成功注册权限数量：{toAdd.Count}");
        }
    }
}